package com.edu.zut.service.Impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.zut.domain.style.*;
import com.edu.zut.entity.PaperTemplate;
import com.edu.zut.mapper.PaperTemplateMapper;
import com.edu.zut.result.HttpCode;
import com.edu.zut.result.ResponseResult;
import com.edu.zut.service.PaperTemplateService;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.util.List;

/**
 * <p>
 * 论文模板表 服务实现类
 * </p>
 *
 * @author 许文科
 * @since 2023-01-12
 */
@Service
public class PaperTemplateServiceImpl extends ServiceImpl<PaperTemplateMapper, PaperTemplate> implements PaperTemplateService {

    @Resource
    private PaperTemplateMapper templateMapper;

    @Value("${templatePath}")
    private String templatePath;

    @Override
    public ResponseResult getTemplateByCollegeName(String collegeName) {
        List<PaperTemplate> templates = templateMapper.getTemplateByCollegeName(collegeName);
        return new ResponseResult(HttpCode.SUCCESS, "成功.", templates);
    }

    /**
     * 根据 coverStyle 创建封面模板
     *
     * @param coverStyle
     * @return
     */
    @Override
    public ResponseResult cover(CoverStyle coverStyle) {
        return new ResponseResult(HttpCode.SUCCESS, "模板创建成功.", null);
    }


//
//<?xml version="1.0" encoding="utf-8"?>
//<Root>
//  <TableStyle>
//    <TableName>
//      <justification>居中</justification>
//      <font>宋体</font>
//      <fontsize>五号</fontsize>
//      <spacelnTotableUp>1</spacelnTotableUp>
//    </TableName>
//    <!-- <InTable>
//      <justification>居中</justification>
//      <font>宋体</font>
//      <enfont>宋体</enfont>
//      <fontsize>五号</fontsize>
//    </InTable>  -->
//  </TableStyle>
//</Root>

    /**
     * 根据 tableStyle 创建表格模板
     *
     * @param tableStyle
     * @return
     */
    @Override
    public ResponseResult table(TableStyle tableStyle) {

        //判断是否存在该文件
        boolean exist = FileUtil.exist(templatePath + "//TableStyle.xml");
        if (exist == true) {
            //删除文件
            FileUtil.del(templatePath + "//TableStyle.xml");
        }

        //创建xml文件
        Document document = DocumentHelper.createDocument();
        //增加节点
        Element TableName = document.addElement("Root")
                .addElement("TableStyle")
                .addElement("TableName");

        //添加值
        TableName.addElement("justification").setText(tableStyle.getJustification());
        TableName.addElement("font").setText(tableStyle.getFont());
        TableName.addElement("fontsize").setText(tableStyle.getFontsize());
        TableName.addElement("spacelnTotableUp").setText(tableStyle.getSpacelnTotableUp().toString());

        //写入磁盘
        writeXML(document, "TableStyle.xml");

        return new ResponseResult(HttpCode.SUCCESS, "模板创建成功.", null);
    }

    @Override
    public ResponseResult catalog(CatalogStyle catalogStyle) {
        //判断是否存在该文件
        boolean exist = FileUtil.exist(templatePath + "//CatalogStyle.xml");
        if (exist == true) {
            //删除文件
            FileUtil.del(templatePath + "//CatalogStyle.xml");
        }
        //创建xml文件
        Document document = DocumentHelper.createDocument();
        //增加节点
        Element root = document.addElement("Root")
                .addElement("Catalog");
        Element title = root.addElement("Title");
        Element text = root.addElement("Text");

        //标题
        title.addElement("necessary").setText(catalogStyle.getNecessary());
        title.addElement("space").setText(catalogStyle.getSpace().toString());
        title.addElement("justification").setText(catalogStyle.getJustification());
        title.addElement("linebetween").setText(catalogStyle.getLineBetween().toString());
//        title.addElement("linebefore").setText(catalogStyle.getLineBefore().toString());
//        title.addElement("lineafter").setText(catalogStyle.getLineAfter().toString());
        title.addElement("CNfont").setText(catalogStyle.getFont());
//        title.addElement("ENfont").setText(catalogStyle.getEnFont());
        title.addElement("fontsize").setText(catalogStyle.getFontSize());
        title.addElement("bold").setText(catalogStyle.getBold().toString());

        //正文
        text.addElement("justification").setText(catalogStyle.getTextJustification());
        text.addElement("linebetween").setText(catalogStyle.getTextLineBetween().toString());
//        text.addElement("linebefore").setText(catalogStyle.getTextLineBefore().toString());
//        text.addElement("lineafter").setText(catalogStyle.getTextLineAfter().toString());
        text.addElement("CNfont").setText(catalogStyle.getTextCnFont());
        text.addElement("ENfont").setText(catalogStyle.getTextEnFont());
        text.addElement("fontsize").setText(catalogStyle.getTextFontSize());

        //写入磁盘
        writeXML(document, "CatalogStyle.xml");
        return new ResponseResult(HttpCode.SUCCESS, "模板创建成功.", null);
    }

    /**
     * 根据 tableStyle 创建表格模板
     *
     * @param headerFooterStyle
     * @return
     */
    @Override
    public ResponseResult headerFooter(HeaderFooterStyle headerFooterStyle) {
        //判断是否存在该文件
        boolean exist = FileUtil.exist(templatePath + "//HeaderFooterStyle.xml");
        if (exist == true) {
            //删除文件
            FileUtil.del(templatePath + "//HeaderFooterStyle.xml");
        }

        //创建xml文档
        Document document = DocumentHelper.createDocument();
        //增加根节点
        Element headerFooter = document.addElement("HeaderFooter");
        //页眉
        Element header = headerFooter.addElement("Header");
        header.addElement("headerJustification").setText(headerFooterStyle.getHeaderJustification());
        header.addElement("CNHeaderFonts").setText(headerFooterStyle.getCnHeaderFonts());
        header.addElement("headerFontsize").setText(headerFooterStyle.getHeaderFontsize());
        //页脚
        Element footer = headerFooter.addElement("Footer");
        footer.addElement("footerJustification").setText(headerFooterStyle.getFooterJustification());
        footer.addElement("CNFooterFonts").setText(headerFooterStyle.getCnFooterFonts());
        footer.addElement("footerFontsize").setText(headerFooterStyle.getFooterFontsize());

        writeXML(document, "HeaderFooterStyle.xml");
        return new ResponseResult(HttpCode.SUCCESS, "成功.", null);
    }

    @Override
    public ResponseResult abstractStyle(AbstractStyle abstractStyle) {

        //判断是否存在该文件
        boolean exist = FileUtil.exist(templatePath + "//AbstractStyle.xml");
        if (exist == true) {
            //删除文件
            FileUtil.del(templatePath + "//AbstractStyle.xml");
        }

        //创建xml文档
        Document document = DocumentHelper.createDocument();
        //增加根节点
        Element abs = document.addElement("Root").addElement("Abstract");

        Element title = abs.addElement("Title");
        title.addElement("necessary").setText(abstractStyle.getNecessary().toString());
        title.addElement("space").setText(abstractStyle.getSpace().toString());
        title.addElement("justification").setText(abstractStyle.getJustification());
        title.addElement("linebetween").setText(abstractStyle.getLineBetween().toString());
        title.addElement("font").setText(abstractStyle.getFont());
        title.addElement("fontsize").setText(abstractStyle.getFontSize());
        title.addElement("bold").setText(abstractStyle.getBold().toString());

        Element text = abs.addElement("Text");
//        text.addElement("indentation").setText(abstractStyle.getTextIndentation().toString());
        text.addElement("linebetween").setText(abstractStyle.getTextLineBetween().toString());
        text.addElement("font").setText(abstractStyle.getTextFont());
        text.addElement("fontsize").setText(abstractStyle.getTextFontSize());
        text.addElement("bold").setText(abstractStyle.getTextBold().toString());

        Element keyword = abs.addElement("keyword");
        keyword.addElement("font").setText(abstractStyle.getKeyChFont());
        keyword.addElement("fontsize").setText(abstractStyle.getKeyChFontSize());

        Element titleE = abs.addElement("TitleE");
        titleE.addElement("necessary").setText(abstractStyle.getNecessaryEn().toString());
        titleE.addElement("justification").setText(abstractStyle.getJustificationEn());
        titleE.addElement("linebetween").setText(abstractStyle.getLineBetweenEn().toString());
        titleE.addElement("font").setText(abstractStyle.getFontEn());
        titleE.addElement("fontsize").setText(abstractStyle.getFontSizeEn());
        titleE.addElement("bold").setText(abstractStyle.getBoldEn().toString());

        Element textE = abs.addElement("TextE");
        textE.addElement("linebetween").setText(abstractStyle.getTextLineBetweenEn().toString());
        textE.addElement("font").setText(abstractStyle.getTextFontEn());
        textE.addElement("fontsize").setText(abstractStyle.getTextFontSizeEn());
        textE.addElement("bold").setText(abstractStyle.getTextBoldEn().toString());

        Element keywordE = abs.addElement("keywordE");
        keywordE.addElement("font").setText(abstractStyle.getKeyFontEn());
        keywordE.addElement("fontsize").setText(abstractStyle.getKeyFontSizeEn());

        writeXML(document, "AbstractStyle.xml");
        return new ResponseResult(HttpCode.SUCCESS, "成功.", null);
    }


    /**
     * 将文件写入磁盘
     *
     * @param fileName
     */
    private void writeXML(Document document, String fileName) {
        //实例化输出格式对象
        OutputFormat format = OutputFormat.createPrettyPrint();
        //设置输出编码
        format.setEncoding("UTF-8");
        //创建需要写入的File对象
        File file = new File(templatePath + "//" + fileName);
        //生成XMLWriter对象，构造函数中的参数为需要输出的文件流和格式
        XMLWriter writer = null;

        try {
            writer = new XMLWriter(new FileOutputStream(file), format);
            //开始写入
            writer.write(document);
            writer.flush();
            writer.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

}
